package com.base.test;

import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.util.Zip4jConstants;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import org.apache.commons.lang3.StringUtils;

/**
 * 压缩方式
 * COMP_STORE = 0;（仅打包，不压缩）
 * COMP_DEFLATE = 8;（默认）
 * COMP_AES_ENC = 99; 加密压缩
 * 压缩级别
 * DEFLATE_LEVEL_FASTEST = 1; (速度最快，压缩比最小)
 * DEFLATE_LEVEL_FAST = 3; (速度快，压缩比小)
 * DEFLATE_LEVEL_NORMAL = 5; (一般)
 * DEFLATE_LEVEL_MAXIMUM = 7;
 * DEFLATE_LEVEL_ULTRA = 9;
 */
public class ZipUtil {
    public static void main(String[] args) {

        try {


            String manhua = "彩画堂";

            // 加密后的 ZIP 文件路径
            String destFilePath = "G:\\漫画原本\\"+manhua  ;


             rname(destFilePath + "\\" + manhua);


            destFilePath +=  "\\";
            String zipFilePath = destFilePath + manhua;
            // 要加密的文件路径
            String srcFilePath = destFilePath  + "迅雷首页搜索：林夕安全屋 海量资源免费赠送.zip";

//            String fileName = "务必不要在线解压会河蟹密码是linxi";
            String password = "linxi";

            String fileName2 = "[漫画]-" + manhua + "-linxi";



            zipFolder(zipFilePath, srcFilePath);


            String destFileName = null;
            String destFileName2 = null;
            if (StringUtils.isNotBlank(destFilePath)) {
//                destFileName = destFilePath + fileName + ".zip";
                destFileName2 = destFilePath + fileName2 + ".zip";
            }


//
//            zip(srcFilePath, destFileName, password);


            zip(srcFilePath, destFileName2, password);

            //unZip(srcFileName,"destFilePath",password);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 压缩
     *
     * @param srcFile 源目录
     * @param dest    要压缩的目录
     * @param passwd  密码 不是必填
     * @throws ZipException 异常
     */
    public static void zip(String srcFile, String dest, String passwd) throws ZipException {
        File srcfile = new File(srcFile);

        //创建目标文件
        String destname = buildDestFileName(srcfile, dest);
        ZipParameters par = new ZipParameters();
        par.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
        par.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);

        if (passwd != null) {
            par.setEncryptFiles(true);
            par.setEncryptionMethod(Zip4jConstants.ENC_METHOD_STANDARD);
            par.setPassword(passwd.toCharArray());
        }

        ZipFile zipfile = new ZipFile(destname);
        if (srcfile.isDirectory()) {
            zipfile.addFolder(srcfile, par);
        } else {
            zipfile.addFile(srcfile, par);
        }
    }

    /**
     * 解压
     *
     * @param zipfile 压缩包文件
     * @param dest    目标文件
     * @param passwd  密码
     * @throws ZipException 抛出异常
     */
    public static void unZip(String zipfile, String dest, String passwd) throws ZipException {
        ZipFile zfile = new ZipFile(zipfile);
        zfile.setFileNameCharset("UTF-8");//在GBK系统中需要设置
        if (!zfile.isValidZipFile()) {
            throw new ZipException("压缩文件不合法，可能已经损坏！");
        }

        File file = new File(dest);
        if (file.isDirectory() && !file.exists()) {
            file.mkdirs();
        }

        if (zfile.isEncrypted()) {
            zfile.setPassword(passwd.toCharArray());
        }
        zfile.extractAll(dest);
    }

    /**
     * 创建目标文件
     *
     * @param srcfile
     * @param dest
     * @return
     */
    public static String buildDestFileName(File srcfile, String dest) {
        if (dest == null) {
            if (srcfile.isDirectory()) {
                dest = srcfile.getParent() + File.separator + srcfile.getName() + ".zip";
            } else {
                String filename = srcfile.getName().substring(0, srcfile.getName().lastIndexOf("."));
                dest = srcfile.getParent() + File.separator + filename + ".zip";
            }
        } else {
            createPath(dest);//路径的创建
            if (dest.endsWith(File.separator)) {
                String filename = "";
                if (srcfile.isDirectory()) {
                    filename = srcfile.getName();
                } else {
                    filename = srcfile.getName().substring(0, srcfile.getName().lastIndexOf("."));
                }
                dest += filename + ".zip";
            }
        }
        return dest;
    }

    /**
     * 创建指定路径
     *
     * @param dest
     */
    private static void createPath(String dest) {
        File destDir = null;
        if (dest.endsWith(File.separator)) {
            destDir = new File(dest);//给出的是路径时
        } else {
            destDir = new File(dest.substring(0, dest.lastIndexOf(File.separator)));
        }

        if (!destDir.exists()) {
            destDir.mkdirs();
        }
    }




    private static void rname(String directoryPath) {
        // 创建File对象表示文件夹
        File directory = new File(directoryPath);

        // 确保文件夹存在
        if (directory.exists() && directory.isDirectory()) {
            // 获取文件夹下所有文件
            File[] files = directory.listFiles();
            // 遍历文件数组
            for (File file : files) {
                // 检查文件名是否以指定前缀开始
                if (file.getName().contains("小脚冰凉")) {
                    // 新文件名 = 指定的新前缀 + 原文件名（不包含指定的旧前缀）
                    String newFileName = file.getName().replace("店名：小脚冰凉 欢迎光临", "迅雷首页搜索：林夕安全屋 海量资源免费赠送");
                    // 创建新的File对象表示新文件路径
                    File newFile = new File(directory, newFileName);
                    // 重命名文件
                    if (file.renameTo(newFile)) {
                        System.out.println("File renamed from " + file.getName() + " to " + newFileName);
                    } else {
                        System.out.println("Failed to rename " + file.getName());
                    }
                }else if (file.getName().contains("文字文稿")) {
                    // 新文件名 = 指定的新前缀 + 原文件名（不包含指定的旧前缀）
                    String newFileName = file.getName().replace("文字文稿", "迅雷首页搜索：林夕安全屋 海量资源免费赠送");
                    // 创建新的File对象表示新文件路径
                    File newFile = new File(directory, newFileName);
                    // 重命名文件
                    if (file.renameTo(newFile)) {
                        System.out.println("File renamed from " + file.getName() + " to " + newFileName);
                    } else {
                        System.out.println("Failed to rename " + file.getName());
                    }
                } if (file.getAbsolutePath().contains("pdf")){
                    String newFileName = "迅雷首页搜索：林夕安全屋 海量资源免费赠送_" + file.getName();
                    // 创建新的File对象表示新文件路径
                    File newFile = new File(directory, newFileName);
                    // 重命名文件
                    if (file.renameTo(newFile)) {
                        System.out.println("File renamed from " + file.getName() + " to " + newFileName);
                    } else {
                        System.out.println("Failed to rename " + file.getName());
                    }
                }




            }
        } else {
            System.out.println("The directory does not exist or is not a directory.");
        }
    }



    public static void zipFolder(String folderPath, String zipFilePath) throws IOException {
        File folder = new File(folderPath);
        FileOutputStream fos = new FileOutputStream(zipFilePath);
        ZipOutputStream zos = new ZipOutputStream(fos);

        addFolderToZip("", folder, zos);
        zos.close();
        fos.close();
    }

    private static void addFolderToZip(String path, File folder, ZipOutputStream zos) throws IOException {
        for (File file : folder.listFiles()) {
            if (file.isDirectory()) {
                addFolderToZip(path + "/" + file.getName(), file, zos);
            } else {
                byte[] buffer = new byte[1024];
                FileInputStream fis = new FileInputStream(file);
                zos.putNextEntry(new ZipEntry(path + "/" + file.getName()));
                int length;
                while ((length = fis.read(buffer)) > 0) {
                    zos.write(buffer, 0, length);
                }
                zos.closeEntry();
                fis.close();
            }
        }
    }
}